package com.goddess.yeecolor.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.goddess.yeecolor.Modle.BoutiqueModle;
import com.goddess.yeecolor.Modle.CurriculumModle;
import com.goddess.yeecolor.Modle.PublicModle;
import com.goddess.yeecolor.Modle.SlideModle;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.LoginAcitivity;
import com.goddess.yeecolor.adapter.ExerciseFragmentPagerAdapter;
import com.goddess.yeecolor.adapter.PublicFragmentViewPagerAdapter;
import com.goddess.yeecolor.base.BaseFragment;
import com.goddess.yeecolor.fragment.CollegeFragmentGraceAllFragment.BoutiqueFragment;
import com.goddess.yeecolor.fragment.CollegeFragmentGraceAllFragment.CurriculumFragment;
import com.goddess.yeecolor.fragment.CollegeFragmentGraceAllFragment.PublicFragment;
import com.goddess.yeecolor.tools.CookieUtils;
import com.goddess.yeecolor.tools.ImageUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.view.NoScrollViewPager;
import com.goddess.yeecolor.view.ZoomOutPageTransformer;
import com.goddess.yeecolor.webview.PublicFragmentViewpagerWebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.goddess.yeecolor.tools.MyUrl.TAG;

/**
 * 学院
 */
public class CollegeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private View mView;
    //图片轮播ViewPager
    private ViewPager viewPager;
    private TabLayout idTabLayout;
    private NoScrollViewPager idViewPager;
    private ExerciseFragmentPagerAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private AppBarLayout appbarLayout;

    private List<String> mTitleList;
    private List<Fragment> fragmentList;
    private PublicFragment publicFragment;
    private CurriculumFragment curriculumFragment;
    private BoutiqueFragment boutiqueFragment;
    private MyPagerAdapter pagerAdapter;
    private List<SlideModle> slideModles=new ArrayList<>();

    TabLayout.Tab tab1;
    TabLayout.Tab tab2;
    TabLayout.Tab tab3;

    private static final int FRAGMENT1 = 0;
    private static final int FRAGMENT2 = 1;
    private static final int FRAGMENT3 = 2;

    //请求数据用来传参的Map
    private Map<Object,Object> map;

    //记录分页 页数
    private int page=1;
    //记录上拉下拉状态
    private String PULL_STATE="";


    //公开个数据数据集合
    List<PublicModle> modleList=new ArrayList<>();

    private List<BoutiqueModle> modles2=new ArrayList<>();

    private List<CurriculumModle> modles3=new ArrayList<CurriculumModle>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView=inflater.inflate(R.layout.fragment_college,container,false);
            initFindView();
            onRefresh();
            initData();
            initOnClck();
        }
        return mView;
    }

    @Override
    public void initOnClck() {
        /**
         * 轮播图的ViewPager与下拉刷新的手势冲突的事件拦截分发处理
         */
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        swipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        swipeRefreshLayout.setEnabled(true);
                        break;
                }
                return false;
            }
        });

        /**
         * ViewPager的与下拉刷新冲突的事件拦截分发处理
         */
        idViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        swipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        swipeRefreshLayout.setEnabled(true);
                        break;
                }
                return false;
            }
        });

        //SwipeRefreshLayout下拉刷新事件处理: 下面:onRefresh()方法
        swipeRefreshLayout.setOnRefreshListener(this);

        /**
         * AppBarLayout与SwipeRefreshLayout下拉刷新事件分发处理
         */
        appbarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        });
        CookieUtils.getInstence().setOnItemClickListener(new PublicFragmentViewPagerAdapter.OnItemClicklistener() {
            @Override
            public void OnItemClick(View view, int position) {
                String uuid= SharePreceUtils.getOther("user","unique");
                if(!"".equals(uuid)){
                    Intent intent=new Intent();
                    intent.setClass(getActivity(),PublicFragmentViewpagerWebView.class);
                    intent.putExtra("id",String.valueOf(modleList.get(position).getId()));
                    intent.putExtra("webview",modleList.get(position).getWebview());
                    intent.putExtra("price",modleList.get(position).getPrice());
                    Log.e(MyUrl.TAG,"ididididi"+modleList.get(position).getId()+"position"+position);
                    startActivity(intent);
                }else{
                    Intent intent=new Intent(getContext(),LoginAcitivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void initFindView() {
        swipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeRefresh_layout);
        appbarLayout = (AppBarLayout) mView.findViewById(R.id.app_bar);

        //设置轮播图
        viewPager = (ViewPager) mView.findViewById(R.id.viewpager);
        pagerAdapter = new MyPagerAdapter(slideModles, getContext());

        //设置ViewPager相关
        idTabLayout = (TabLayout) mView.findViewById(R.id.tab_layout);
        idViewPager = (NoScrollViewPager) mView.findViewById(R.id.view_pager);



        //设置Fragment集合
        fragmentList = new ArrayList<>();
        publicFragment = new PublicFragment();
        boutiqueFragment = new BoutiqueFragment();
        curriculumFragment = new CurriculumFragment();
        fragmentList.add(publicFragment);
        fragmentList.add(boutiqueFragment);
        fragmentList.add(curriculumFragment);

        //设置Title集合
        mTitleList = new ArrayList<>();
        mTitleList.add("优雅公开课");
        mTitleList.add("优雅精品课");
        mTitleList.add("优雅课程表");

        //设置TabLayout标示
        tab1 = idTabLayout.getTabAt(FRAGMENT1);
        tab2 = idTabLayout.getTabAt(FRAGMENT2);
        tab3 = idTabLayout.getTabAt(FRAGMENT3);

        //控制ViewPager是否可以左右滑动(true表示不可以)
        //  idViewPager.setNoScroll(true);


        // 设置ViewPager关联title
        idTabLayout.setTabMode(TabLayout.MODE_FIXED);
        adapter = new ExerciseFragmentPagerAdapter(getActivity().getSupportFragmentManager(), fragmentList, mTitleList);
        idViewPager.setAdapter(adapter);
        idTabLayout.setupWithViewPager(idViewPager);
    }

    @Override
    public void initData() {
        viewPagerInitData();
    }

    /**
     * 轮播ViewPaegr的数据
     */
    public void viewPagerInitData(){
        String url = MyUrl.SLIDE;
        Map<Object, Object> map = new HashMap<>();
        map.put("unique", SharePreceUtils.getOther("user", "unique"));
        Log.e(TAG, SharePreceUtils.getOther("user", "unique"));
        OkttpUtils.getIntence().OkttpPost(url, map, handler, 1);
    }

    /**
     * SwipeRefreshLayout下拉刷新事件处理
     */
    @Override
    public void onRefresh() {
        PULL_STATE="BOTTOM";
        String url= MyUrl.COLLEGE_CURRICU;
        switch (idViewPager.getCurrentItem()) {
            case FRAGMENT1:
                map=new HashMap<>();
                map.put("unique", SharePreceUtils.getOther("user","unique"));
                map.put("typed","1");
                map.put("page",page+"");
                OkttpUtils.getIntence().OkttpPost(url,map,handler,2);
                publicFragment.setData(modleList);
                break;
            case FRAGMENT2:
                map=new HashMap<>();
                map.put("unique", SharePreceUtils.getOther("user","unique"));
                map.put("typed","2");
                map.put("page",page+"");
                OkttpUtils.getIntence().OkttpPost(url,map,handler,3);
                swipeRefreshLayout.setRefreshing(false);
                break;
            case FRAGMENT3:
                map=new HashMap<>();
                map.put("unique", SharePreceUtils.getOther("user","unique"));
                map.put("typed","0");
                map.put("page",page+"");
                OkttpUtils.getIntence().OkttpPost(url,map,handler,4);
                swipeRefreshLayout.setRefreshing(false);
                break;
        }

    }
    /**
     * 轮播图的ViewPager的数据解析
     */
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                String jsonString =msg.getData().getString("result");
                JSONObject jsonObject=new JSONObject(jsonString);
                int code=jsonObject.getInt("code");
                if(code==100){
                    if(msg.what==1){
                        JSONArray jsonArray=jsonObject.getJSONArray("result");
                        for (int i=0;i<jsonArray.length();i++){
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);
                            SlideModle slideModle=new SlideModle();
                            slideModle.setImgurl(jsonObject1.getString("recommend_thumb"));
                            slideModle.setWebciewurl(jsonObject1.getString("webview"));
                            slideModle.setId(jsonObject1.getString("id"));
                            slideModle.setState(jsonObject1.getInt("state"));
                            slideModle.setTitle(jsonObject1.getString("title"));
                            slideModle.setPrice(jsonObject1.getString("price"));
                            slideModle.setData(jsonObject1.getString("start_date"));
                            swipeRefreshLayout.setRefreshing(false);
                            slideModles.add(slideModle);
                        }
                    }else if(msg.what==2){
                        JSONArray result=jsonObject.getJSONArray("result");
                        for (int i=0;i<result.length();i++){
                            JSONObject object1=result.getJSONObject(i);
                            PublicModle modle=new PublicModle();
                            modle.setId(object1.getString("id"));
                            modle.setState(object1.getInt("state"));
                            modle.setImage(object1.getString("thumb"));
                            modle.setTitle(object1.getString("title"));
                            modle.setPrice(object1.getString("price"));
                            modle.setData(object1.getString("start_date"));
                            modle.setWebview(object1.getString("webview"));
                            modleList.add(modle);
                        }

//                        if (swipeRefreshLayout.isRefreshing()) {
//                            swipeRefreshLayout.setRefreshing(false);
//                        }
                    }else if(msg.what==3) {
                        JSONArray array = jsonObject.getJSONArray("result");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object1 = array.getJSONObject(i);
                            BoutiqueModle modle = new BoutiqueModle();
                            modle.setTitle(object1.getString("title"));
                            modle.setPrice(object1.getString("price"));
                            modle.setData(object1.getString("start_date"));
                            modle.setImage(object1.getString("thumb"));
                            modle.setState(object1.getInt("state"));
                            modle.setWebview(object1.getString("webview"));
                            modles2.add(modle);
                        }
                        boutiqueFragment.setData(modles2);
                    }else if(msg.what==4) {
                        JSONArray array=jsonObject.getJSONArray("result");
                        for (int i=0;i<array.length();i++){
                            JSONObject object1=array.getJSONObject(i);
                            CurriculumModle modle=new CurriculumModle();
                            modle.setTitle(object1.getString("title"));
                            modle.setName(object1.getString("tech"));
                            modle.setWord(object1.getString("info"));
                            modle.setDate(object1.getString("start_date"));
                            modle.setState(object1.getInt("state"));
                            modle.setWebview(object1.getString("webview"));
                            modles3.add(modle);
                        }
                        curriculumFragment.setData(modles3);
                    }
                }
                if (PULL_STATE.equals("BOTTOM")) {
                    swipeRefreshLayout.setRefreshing(false);
                }
                viewPager.setAdapter(pagerAdapter);
                viewPager.setOffscreenPageLimit(4);
                viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
                adapter.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    };


    /**
     * 轮播图的ViewPager的适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        private List<SlideModle> slideModles;
        private Context context;

        public MyPagerAdapter( List<SlideModle> slideModles, Context context) {
            this.slideModles = slideModles;
            this.context = context;
        }
        @Override
        public int getCount() {
            return slideModles.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(getActivity());
            ImageUtils.getInstance().ImageStart(context,slideModles.get(position).getImgurl(),imageView);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            container.addView(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CookieUtils.getInstence().onItemClickListener.OnItemClick(v,position);
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((ImageView) object);
        }
    }

}
